package com.muse.app.service;

import com.google.common.collect.ImmutableMap;
import com.muse.app.dao.UserDao;
import com.muse.appManage.service.ManageUserService;
import com.muse.constant.Constant;
import com.muse.constant.ManageRole;
import com.muse.constant.RedisKey;
import com.muse.constant.Role;
import com.muse.entity.Result;
import com.muse.entity.UserInfo;
import com.muse.model.*;
import com.muse.sqlutils.SqlBuilder;
import com.muse.utils.ObjectCopy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.muse.sqlutils.SqlBuilder.eq;

/**
 * Created with IntelliJ IDEA.
 * User: lee
 * Date: 2021/4/19
 * Time: 8:33 下午
 * Description:
 */
@Service
@Slf4j
public class UserService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserDao userDao;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Value("${default.avatar}")
    private String defaultAvatar;

    @Autowired
    private ManageUserService manageUserService;


    public Result<UserInfoVo> login(LoginParam param) {
//        String code="1816";
        String code = redisTemplate.opsForValue().get(RedisKey.SMS_CODE_LOGIN + param.getPhone());

        if (StringUtils.isEmpty(code)) {
            return Result.failure("验证码已失效", null);
        }
        if (!code.equals(param.getCode())) {
            return Result.failure("验证码不正确", null);
        } else {
            UserInfoVo vo = new UserInfoVo();
            UserInfo userInfo = userDao.getUserInfoByPhone(param.getPhone());
            if (userInfo == null) {
                UserInfo newUser = new UserInfo();
                newUser.setPhone(param.getPhone());
                newUser.setMemberId(System.currentTimeMillis() / 100);
                newUser.setRole(Role.BROW_TATTOOER.getValue());
                newUser.setManageRole(ManageRole.UNKNOWN.getValue());
                newUser.setAvatar(defaultAvatar);
                newUser.setUserName(UUID.randomUUID().toString());
                long id = SqlBuilder.insertReturnId("t_user", newUser, jdbcTemplate);
                newUser.setId((int) id);
                ObjectCopy.copy(newUser, vo);
            } else {
                ObjectCopy.copy(userInfo, vo);
            }
            String token = UUID.randomUUID().toString();
            vo.setToken(Constant.APP_TOKEN + token);
            vo.setRoleName(Role.getRoleByValue(vo.getRole()).getName());

            vo.setManageRoleName(ManageRole.getManageRoleByValue(vo.getManageRole()).getName());
            redisTemplate.opsForValue().set(RedisKey.TOKEN + Constant.APP_TOKEN + token, String.valueOf(vo.getId()));
            redisTemplate.delete(RedisKey.SMS_CODE_LOGIN + param.getPhone());

//            jedis.set(RedisKey.TOKEN + Constant.APP_TOKEN + token, String.valueOf(vo.getId()));
//            jedis.del(RedisKey.SMS_CODE_LOGIN + param.getPhone());
            return Result.success(vo);
        }
    }

    public UserInfo getUserByToken(String token) {
        String id = redisTemplate.opsForValue().get(RedisKey.TOKEN + token);
        if (StringUtils.isEmpty(id)) {
            log.info("redis token is null,token={}", token);
            return null;
        }
        return userDao.getUserInfoById(Integer.parseInt(id));
    }


    public Result out(String token) {
        try {
            redisTemplate.delete(RedisKey.TOKEN + token);
            return Result.success();
        } catch (Exception e) {
            log.error("login out error", e);
            return Result.failure();
        }
    }

    public Result<UserInfoVo> me(Integer id) {
        UserInfo userInfo = userDao.getUserInfoById(id);
        return Result.success(manageUserService.convertUserInfoVo(userInfo));
    }

    public Result updateUserInfo(UpdateUserParam param, int id) {
        Map<String, Object> updateParam = new HashMap<>();
        if (!StringUtils.isEmpty(param.getAvatar())) {
            updateParam.put("avatar", param.getAvatar());
        }
        if (!StringUtils.isEmpty(param.getUserName())) {
            updateParam.put("user_name", param.getUserName());
        }
        SqlBuilder.update("t_user", updateParam)
                .where(
                        eq("id", id)
                ).execute(jdbcTemplate);

        return Result.success();
    }

    public Result updatePhoneParam(updatePhoneParam param, Integer id) {
        String code = redisTemplate.opsForValue().get(RedisKey.SMS_CODE_UPDATE_PHONE + param.getOldPhone());

        if (StringUtils.isEmpty(code)) {
            return Result.failure("验证码已失效", null);
        }
        if (!code.equals(param.getCode())) {
            return Result.failure("验证码不正确", null);
        }
        SqlBuilder.update("t_user", ImmutableMap.of("phone", param.getNewPhone()))
                .where(
                        eq("id", id)
                ).execute(jdbcTemplate);
        redisTemplate.delete(RedisKey.SMS_CODE_UPDATE_PHONE + param.getOldPhone());
        return Result.success();
    }
}
